package com.bdqn.t382.controller;

import com.bdqn.t382.entity.SysUser;
import com.bdqn.t382.ex.LoginException;
import com.bdqn.t382.service.SysUserService;
import com.bdqn.t382.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;


@Controller
public class LoginController extends BaseController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 获取 request 对象
     */

    public String forward(String url) {
        return UrlBasedViewResolver.FORWARD_URL_PREFIX + url;
    }

    public HttpServletRequest request() {
        return request;
    }

    public HttpSession session() {
        // 通过 request 对象可以获取到 session
        return request().getSession();
    }

    /**
     * 负责重定向任意路径
     */
    public String redirect(String url) {
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX + url;
    }

    @GetMapping("/login")
    public String toLogin() {
        // 调用 forward 方法，则减少了自己拼接写出的风险
        return forward("/login.jsp");
    }

    @PostMapping("/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password) {
        SysUser loginUser = sysUserService.login(account, password);
        if (loginUser != null) {
            session(Constants.SESSION_USER, loginUser);
            return redirect("/main/index");
        } else {
            // 登录失败抛出异常
            throw new LoginException("登录失败，用户名或密码错误！");
        }
    }

    @GetMapping("/ex")
    public void throwException() {
        throw new RuntimeException("测试不同异常映射到不同页面！");
    }


    @ExceptionHandler(value = RuntimeException.class)
    public String handlerException(RuntimeException e, HttpServletRequest request) {
        // 设置捕获的错误对象到 request 作用域
        request.setAttribute(Constants.REQUEST_ERROR, e);
        // 跳转异常页面：/WEB-INF/jsp/500.jsp
        return "500";
    }

    // 跳转到后台首页
    @GetMapping("/main/index")
    public String index() {
        return "index";
    }
}
